import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sph_driver/AppConfig/Config.dart';
import 'package:sph_driver/AppConfig/LocalStorage.dart';

import '../AppConfig/RouteAct.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../http/NoLoadingGetApi.dart';
import '../http/api.dart';

import 'SourceDetails.dart';
import '../http/getapi.dart';
class CheckedGoodsList extends StatefulWidget {
  const CheckedGoodsList({super.key, });
  @override
  State<CheckedGoodsList> createState() => _CheckedGoodsListState();
}

class _CheckedGoodsListState extends State<CheckedGoodsList> {
  List goodsList=[];
  int isCheck=-1;
  Map sourceDetailsMap={};
  int pageNum=1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getDetailsAction();
  }
  //获取货源
  void getDetailsAction() async {
    String? drvId=await UserIdManager.getUserID();
        NoLoadinggetApiManager.getData(
        context,
        "api/goods/goods/driverContactGoodsPage",
        {
          "driverId":drvId,
          "current":pageNum,
          "size":20,
        },
            (responseData) async {
          setState(() {
            if(pageNum==1){
              goodsList = responseData['data']['records'];
            }else {
              if(responseData['data']['records'].isNotEmpty) {
                goodsList.add(responseData['data']['records']);
              }else{
                pageNum =--pageNum;
              }
            }
          });
        },
      );
  }
  //货源详情
  void getSourceDetailsAction(Map dataMap) async {
    String? drvId=await UserIdManager.getUserID();
    NoLoadinggetApiManager.getData(
      context,
      MyServiceUrl.getLoginUser,
      {},
          (responseData) async {
        Navigator.push( context, FadeRoute(page:SourceDetails(
          dataMap: dataMap,
        )));
      },
    );
  }

  Future _onRefresh() async {
    pageNum=1;
    getDetailsAction();

  }
  Future _onLoadfresh() async{
    if(goodsList.length > 20*pageNum-1){
      pageNum++;
      getDetailsAction();
    }

  }
  ScrollController _scrollController = ScrollController();
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Colors.white,
        title: Text("联系记录",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w300),),
      ),
      body:   EasyRefresh(
        header:
        ClassicHeader(
          dragText: '下拉刷新',
          armedText: '准备释放',
          readyText: '加载中...',
          processingText: '加载中...',
          processedText: '刷新成功',
          noMoreText: '暂无更多',
          failedText: '刷新失败',
          messageText: '刷新时间 %T',
        ),
        footer: ClassicFooter(
          dragText: '加载更多',
          armedText: '准备释放',
          readyText: '加载中...',
          processingText: '加载中...',
          processedText: '加载成功',
          noMoreText: '暂无更多',
          failedText: '加载失败',
          messageText: '加载时间 %T',
        ),
        onRefresh: _onRefresh,
        onLoad:goodsList.length>20*pageNum-1? _onLoadfresh:null,
        child:
      ListView(
        children: [

            goodsList.length==0?
                Container(height: screenSize.height-100.h,color: Colors.white,
                child:  BrnAbnormalStateWidget(
                  img: Image.asset(
                    'lib/Images/OrderList/找货暂无货源.png',
                    scale: 3.0,
                  ),
                  content: '暂无货源',
                ),)

                :Container(
              color: MyColors.backgreyColor,
              height: screenSize.height-80.h,
              padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),

              child:  ListView.builder(
                  padding: EdgeInsets.zero, // 设置padding为零
                  shrinkWrap: true,
                  itemCount:  goodsList.length,
                  controller: _scrollController,
                  itemBuilder: (BuildContext context,
                      int index) {
                    return GestureDetector(
                      child: Container(
                        margin: EdgeInsets.only(bottom: 8.h,),
                        padding: EdgeInsets.only(top: 8.h,bottom: 8.h,left: 10.w,right: 10.w),
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.all(Radius.circular(10))),
                        child:Column(
                            children: [
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  if(goodsList[index]['category']==1)
                                    Image.asset("lib/Images/OrderList/企业标签.png",width: 30.w,height: 18.h,),
                                  if(goodsList[index]['invoiceType']==1)
                                    SizedBox(width: 8.w,),
                                  if(goodsList[index]['invoiceType']==1)
                                    Image.asset("lib/Images/OrderList/专票标签.png",width: 30.w,height: 18.h,),
                                ],
                              ),
                              Row(
                                children: [
                                  Column(
                                    children: [
                                      Image.asset("lib/Images/OrderList/装icon.png",
                                        width: 15.w, height: 15.h,),
                                      Image.asset(
                                        "lib/Images/OrderList/垂直虚线.png", width: 18.w,
                                        height: 10.h,),
                                      if(goodsList[index]["loadPlaceInfo"].length == 2&&goodsList[index]["loadPlaceInfo"][1]!=null&&goodsList[index]["loadPlaceInfo"][1]!="null")
                                        Column(
                                          children: [
                                            Image.asset(
                                              "lib/Images/OrderList/装icon.png",
                                              width: 15.w, height: 15.h,),
                                            Image.asset(
                                              "lib/Images/OrderList/垂直虚线.png",
                                              width: 18.w, height: 10.h,),
                                          ],
                                        ),
                                      if( goodsList[index]["unloadPlaceInfo"].length == 2&&goodsList[index]["unloadPlaceInfo"][1]!=null&&goodsList[index]["loadPlaceInfo"][1]!="null")
                                        Column(
                                          children: [
                                            Image.asset(
                                              "lib/Images/OrderList/卸icon.png",
                                              width: 15.w, height: 15.h,),
                                            Image.asset(
                                              "lib/Images/OrderList/垂直虚线.png",
                                              width: 18.w, height:10.h,),
                                          ],
                                        ),
                                      Image.asset("lib/Images/OrderList/卸icon.png",
                                        width: 15.w, height: 15.h,),
                                    ],
                                  ),

                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,

                                    children: [
                                      // SizedBox(height: 8.h,),
                                      Row(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          if(goodsList[index]["loadPlaceInfo"].length>0)
                                            Container(
                                              width: screenSize.width/3,
                                              child:   Text(

                                                goodsList[index]["loadPlaceInfo"][0]["city"] +
                                                    "-" +
                                                    goodsList[index]["loadPlaceInfo"][0]["county"] ,
                                                style: TextStyle(
                                                    color: Colors.black, fontSize: 14.sp,overflow: TextOverflow.ellipsis,fontWeight: FontWeight.w600),),
                                            ),

                                          SizedBox(width: 8.w,),
                                          if(goodsList[index]['loadDay']!=null)
                                          Container(
                                            width:screenSize.width/3,
                                            child:  Text(goodsList[index]['loadDay']+" "+goodsList[index]['loadTime']+"点装货",overflow: TextOverflow.ellipsis,
                                              style: TextStyle(color: MyColors.textColor, fontSize: 12.sp),),
                                          ),
                                        ],
                                      ),
                                      SizedBox(height: 8.h,),
                                      if(goodsList[index]["loadPlaceInfo"].length == 2&&goodsList[index]["loadPlaceInfo"][1]!=null&&goodsList[index]["loadPlaceInfo"][1]!="null")
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              children: [
                                                Container(
                                                  width: screenSize.width/3,
                                                  child:   Text(

                                                    goodsList[index]["loadPlaceInfo"][1]["city"] +
                                                        "-" +
                                                        goodsList[index]["loadPlaceInfo"][1]["county"] ,
                                                    style: TextStyle(
                                                        color: Colors.black, fontSize: 14.sp,overflow: TextOverflow.ellipsis,fontWeight: FontWeight.w600),),
                                                ),
                                              ],
                                            ),


                                            SizedBox(height: 8.h,),
                                          ],
                                        ),

                                      Row(
                                        children: [
                                          if(goodsList[index]["unloadPlaceInfo"].lengyth>0)
                                          Container(
                                            width: screenSize.width/3,
                                            child:
                                            Text(
                                              goodsList[index]["unloadPlaceInfo"][0]["city"] +
                                                  "-" +
                                                  goodsList[index]["unloadPlaceInfo"][0]["county"],
                                              style: TextStyle(overflow: TextOverflow.ellipsis,
                                                  color: Colors.black, fontSize: 14.sp,fontWeight: FontWeight.w600),),
                                          ),
                                          SizedBox(width: 8.w,),
                                          if(goodsList[index]["unloadTime"] !=null)
                                            Container(
                                              width: screenSize.width/3,
                                              child:  Text(goodsList[index]['unloadDay']+" "+goodsList[index]['unloadTime']+"点卸货",overflow: TextOverflow.ellipsis,
                                                style: TextStyle(color: MyColors.textColor, fontSize: 12.sp),),

                                            ),

                                        ],
                                      ),
                                      if(goodsList[index]["unloadPlaceInfo"].length == 2&&goodsList[index]["unloadPlaceInfo"][1]!=null&&goodsList[index]["unloadPlaceInfo"][1]!="null")
                                        Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            SizedBox(height: 8.h,),
                                            Row(
                                              children: [
                                                Container(
                                                  width: screenSize.width/3,
                                                  child:
                                                  Text(
                                                    goodsList[index]["unloadPlaceInfo"][1]["city"] +
                                                        "-" +
                                                        goodsList[index]["unloadPlaceInfo"][1]["county"],
                                                    style: TextStyle(overflow: TextOverflow.ellipsis,
                                                        color: Colors.black, fontSize: 14.sp,fontWeight: FontWeight.w600),),
                                                ),
                                                SizedBox(width: 8.w,),

                                              ],
                                            ),


                                          ],
                                        ),

                                    ],

                                  ),
                                 
                                ],

                              ),
                              SizedBox(height:8.h),

                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                               crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Row(
                                        children: [
                                          SizedBox(width: 5.w,),
                                          if( goodsList[index]["cargoInfo"][0]["cargoName"]!=null)
                                            Text(goodsList[index]["cargoInfo"][0]["cargoName"],  style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                          if( goodsList[index]["cargoInfo"][0]["cargoWeight"]!=null)
                                            Text(","+goodsList[index]["cargoInfo"][0]["cargoWeight"].toString() + "吨",  style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                          if( goodsList[index]["cargoInfo"][0]["cargoVolume"]!=null)
                                            Text( ","+goodsList[index]["cargoInfo"][0]["cargoVolume"].toString() + "方", style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                          if( goodsList[index]["cargoInfo"][0]["packageType"]!=null)
                                            Text( ","+goodsList[index]["cargoInfo"][0]["packageType"].toString(), style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                        ],
                                      ),

                                    ],
                                  ),
                                  Row(
                                    children: [
                                      SizedBox(width: 5.w,),
                                      goodsList[index]["vehicleLength"].contains(",")?
                                      Text( goodsList[index]["vehicleLength"].replaceAll(",", "米/")+"米",style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),):
                                      Text( goodsList[index]["vehicleLength"]+"米",style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),
                                      if(goodsList[index]["vehicleModel"]!=null)
                                        goodsList[index]["vehicleLength"].contains(",")?
                                        Text("丨"+goodsList[index]["vehicleModel"].replaceAll(",", "/"),style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),)
                                            : Text("丨"+goodsList[index]["vehicleModel"],style: TextStyle(color: MyColors.textColor, fontSize: 13.sp),),

                                    ],
                                  ),
                                  int.parse(goodsList[index]["type"].toString()) == 0?
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      SizedBox(width: 5.w,),
                                      Text((goodsList[index]["freight"]).toString(),
                                        style: TextStyle(color: MyColors.themeColor,
                                            fontSize: 20.sp,
                                            fontWeight: FontWeight.w600),),
                                      Column(
                                        children: [
                                          Text("元/趟",  style: TextStyle(
                                              color: MyColors.themeColor,
                                              fontSize: 12.sp,
                                              fontWeight: FontWeight.w600), ),
                                          SizedBox(height: 3.h,),
                                        ],
                                      ),


                                    ],
                                  )
                                      :Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Text("电议", style: TextStyle(
                                          color: MyColors.themeColor,
                                          fontSize: 20.sp,
                                          fontWeight: FontWeight.w600),),
                                    ],
                                  ),

                                ],
                              ),
                              if(goodsList[index]['status']!=1)
                                Image.asset("lib/Images/OrderList/找货货源已下架icon.png",width:60.w,height: 60.h,),

                            ],
                          ),

                              Divider(height: 1.h,color: MyColors.backgreyColor,),
                              SizedBox(height: 6.h,),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    children: [
                                      Container(
                                        decoration: BoxDecoration(
                                            color: Colors.white,
                                            borderRadius: BorderRadius.all(Radius.circular(10))),
                                        child: ClipRRect(
                                          borderRadius: BorderRadius.all(Radius.circular(10)),
                                          child: goodsList[index]['avatarPath']!=""&&goodsList[index]['avatarPath']!=null?Image.network(
                                            MyServiceUrl.imgHeader + goodsList[index]['avatarPath'],
                                            width: 36.w,
                                            height: 36.h,
                                            fit: BoxFit.cover,
                                          ):Image.asset("lib/Images/login/默认头像.jpeg",width: 36.w, height: 36.h, fit: BoxFit.cover,),
                                        ),
                                      ),
                                      SizedBox(width: 8.w,),
                                      Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [

                                          Row(
                                            children: [
                                              if(goodsList[index]['realName']!=null)
                                                Text(goodsList[index]['realName'],style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                              SizedBox(width: 4.w,),
                                              if(goodsList[index]['rating']!=null)
                                                BrnTagCustom(
                                                  tagText: "信用"+(divideAndRound(goodsList[index]['rating'], 20)).toString()+"星",
                                                  backgroundColor: Color.fromRGBO(251, 236, 228, 1),
                                                  textColor: MyColors.themeColor,
                                                ),
                                            ],
                                          ),
                                          if(goodsList[index]['totalNum']!=null&&goodsList[index]['rating']!=null)
                                            Text("交易  "+goodsList[index]['totalNum'].toString()+"  "+"好评率  "+goodsList[index]['rating']+"%"
                                              ,style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                        ],
                                      ),

                                    ],
                                  ),
                                  if(goodsList[index]['status']==1)
                                  BrnSmallMainButton(
                                    title: '去抢单',
                                    bgColor:MyColors.themeColor,
                                    textColor:Colors.white,
                                    width: 80.w,
                                    fontSize: 13.sp,
                                    radius:30,
                                    onTap: ()  async {
                                      // getBatteryInfo();
                                      // String? token= await TokenManager.getToken();
                                      // String sourceId=goodsList[index]['id'];
                                      // String updateTime =goodsList[index]['updateTime'];
                                      // print("sourceId:$sourceId,updateTime:$updateTime");
                                      // dio.interceptors.add(InterceptorsWrapper(
                                      //     onRequest: (options, handler) {
                                      //       options.headers["satoken"] = token;
                                      //       return handler.next(options);
                                      //     }
                                      // ));
                                      //
                                      // dio.get<String>(MyServiceUrl.header+'api/goods/drvUser/user/searchGoodsValidation?updateTime=$updateTime&&sourceId=$sourceId')
                                      //     .then((r) {
                                      //   setState(() {
                                      //     print(r);
                                      //     Map<String, dynamic> jsonMap = json.decode(r.toString());
                                      //
                                      //     // 获取code和data
                                      //     String code = jsonMap['code'].toString();
                                      //     if (code == "200") {
                                      //       getSourceDetailsAction(goodsList[index]['id']);
                                      //     } else {
                                      //
                                      //       BrnToast.show(
                                      //         jsonMap['msg'],
                                      //         context,
                                      //         duration: BrnDuration.short,
                                      //       );
                                      //     }
                                      //     // 打印结果
                                      //     print('Code: $code');
                                      //   });
                                      // }).catchError((error) {
                                      //   print(error);
                                      // });

                                      // if(isCheck==false) {
                                      if(goodsList[index]['status']==1)
                                      getSourceDetailsAction(goodsList[index]);
                                      // setState(() {
                                      //   isCheck=true;
                                      // });
                                      // }
                                    },
                                  )
                                ],
                              ),


                            ]
                        ),
                      ),
                      onTap: (){
                        // if(isCheck==false) {
                        if(goodsList[index]['status']==1)
                        getSourceDetailsAction(goodsList[index]);
                        // setState(() {
                        //   isCheck=true;
                        // });
                        // }

                      },
                    );
                  }
              ),
            ),

        ],
      ),
      ),
    );
  }
}
